package gmone;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class TargetIdMap {
    private static final int MAX_COUNT = 3000;
    private static final int COUNT = 2000;
    private static final int MIN_COUNT = 1000;
    private Map<Long, List<Entry>> targetIdMap = new ConcurrentHashMap<>();
    public static class Entry{
        private Long min;
        private Long max;
        private AtomicInteger count;
        private Entry next;

    }

    public void getTableIndex(Long taskId1, Long targetId) {

        if (!targetIdMap.containsKey(taskId1)) {
            targetIdMap.putIfAbsent(taskId1, new CopyOnWriteArrayList<>());
        }
        CopyOnWriteArrayList<Entry> targetIdList = (CopyOnWriteArrayList)targetIdMap.get(taskId1);
        if (targetIdList.size() < 0) {
            synchronized (targetIdList) {
                Entry entry = new Entry();
                entry.min = targetId;
                entry.max = targetId;
                entry.count.incrementAndGet();
                targetIdList.add(entry);
            }
        }else{
            for (int i = targetIdList.size() - 1; i >= 0; i--) {
                Entry entry = targetIdList.get(i);
                //大于最大数量
                if (targetId > entry.count.get()) {
                    //可以继续添加
                    if (entry.count.get() < COUNT) {
                        synchronized (entry) {
                            entry.max = targetId;
                            entry.count.incrementAndGet();
                        }

                    }//添加新的
                    else{
                        synchronized (targetIdList) {
                            Entry newEntry = new Entry();
                            newEntry.min = targetId;
                            newEntry.max = targetId;
                            newEntry.count.incrementAndGet();
                            targetIdList.add(newEntry);
                        }
                    }
                }
            }
        }
    }
}
